from flask import *
from exts import *
from models import *

baike = Blueprint('baike',__name__,url_prefix='/baike')
@baike.route('/')
def baike_index():
    return "baike页面"

# 获取动物信息
@baike.route('/<int:id>')
def baike_detail(id):
    try:
        animal1 = animal.get_animal_by_id(id)
        # print(animal)
        # for i in range(len(animal)):
            # print(animal[i].id)
        if animal1 == []:
            return jsonify({
                "code": 500,
                "message": f"没有此id的数据",
                "data": None
            })
        else:
            josn = {
                    'id': animal1.id,
                    '全名':animal1.全名,
                    '别名': animal1.别名,
                    '分类': animal1.分类,
                    '体型': animal1.体型,
                    '毛发': animal1.毛发,
                    '智商': animal1.智商,
                    '寿命': animal1.寿命,
                    '饲养': animal1.饲养,
                    '功能': animal1.功能,
                    '原产地': animal1.原产地,
                    '价格': animal1.价格,
                    '简介': animal1.简介,
                    # 'imgUrl': animal1.imgUrl,
                    'imgPath': animal1.imgPath

                }
            json  = {
                "code": 200,
                "message": "获取列表数据成功",
                "data": josn
            }
            return jsonify(json)
    except Exception as e:
        print('错误',e)
        return jsonify({
            "code": 500,
            "message": f"获取列表数据失败: {str(e)}",
            "data": None
        })
    

# 获取动物的数量
@baike.route('/BaikeArticleList/<int:page>/<int:per_page>')
def BaikeArticleList(page,per_page):
    try:
        articlesList = articles.get_article_page(page,per_page)
        # print(articlesList)
        # for i in range(len(articlesList)):
            # print(articlesList[i].id)
        if articlesList == []:
            return jsonify({
                "code": 500,
                "message": f"没有此页的数据",
                "data": None
            })
        else:
            articlesList1=[]
            for i in range(len(articlesList)):
                josn = {
                    'id': articlesList[i].id,
                    'title': articlesList[i].title,
                    'img':getFirstImg(contentUcode(articlesList[i].contents_json)),
                    'content': getFirstText(contentUcode(articlesList[i].contents_json),100),
                    'view_date': articlesList[i].view_date
                }
                articlesList1.append(josn)
            json  = {
                "code": 200,
                "message": "获取列表数据成功",
                "data": articlesList1
            }
            return jsonify(json)
    except Exception as e:
        print('错误',e)
        return jsonify({
            "code": 500,
            "message": f"获取列表数据失败: {str(e)}",
            "data": None
        })
        

# 获取文章的数量
@baike.route('/getArticleNum')
def getArticleNum():
    return jsonify({
        "code": 200,
        "message": "获取列表数据成功",
        "data": articles.query.count()
    })

@baike.route('/Article/<int:id>')
def Article(id):
    try:
        article = articles.getIdArticle(id)
        # print(article)
        if article ==None:
            return jsonify({
                "code": 500,
                "message": f"没有此id的文章",
                "data": None
            })
        else:
            jsonA = {
                'id': article.id,
                'title': article.title,
                'content': contentUcode(article.contents_json),
                'view_date': article.view_date
            }
            return jsonify({
                "code": 200,
                "message": "获取文章数据成功",
                "data": jsonA
            })
    except Exception as e:
        print('错误',e)
        return jsonify({
            "code": 500,
            "message": f"获取列表数据失败: {str(e)}",
            "data": None
        })


# 根据宠物名搜索相关文章
@baike.route('/searchArticles/<pet_name>', methods=['GET'])
@baike.route('/searchArticles/<pet_name>/<category>', methods=['GET'])
@baike.route('/searchArticles/<pet_name>/<category>/<int:page>/<int:per_page>', methods=['GET'])
def search_articles(pet_name, category='全部', page=1, per_page=10):
    try:
        query = articles.query
        
        # 修改搜索条件判断
        if pet_name and pet_name != '-':  # 添加对'-'的判断
            query = query.filter(articles.title.contains(pet_name))
        
        # 修改分类条件判断
        if category and category != '全部':
            query = query.filter(articles.column == category)
        
        # 按查看日期降序排序
        query = query.order_by(articles.view_date.desc())
        
        # 获取总数据量
        total = query.count()
        
        # 执行分页查询
        paginated_articles = query.paginate(page=page, per_page=per_page, error_out=False)
        
        # 构建返回数据
        articles_data = []
        for article in paginated_articles.items:
            articles_data.append({
                'id': article.id,
                'title': article.title,
                'view_date': article.view_date.strftime('%Y-%m-%d %H:%M:%S'),
                'img': getFirstImg(contentUcode(article.contents_json)),
                'content': getFirstText(contentUcode(article.contents_json),100),
                'column': article.column
            })
            
        return jsonify({
            'code': 200,
            'msg': '查询成功',
            'data': articles_data,
            'total': total
        })
        
    except Exception as e:
        print('错误', e)
        return jsonify({
            "code": 500,
            "message": f"查询失败: {str(e)}",
            "data": None
        }), 500  # 添加状态码


def contentUcode(contents_json):
    try:
        return json.loads(contents_json)
    except Exception as e:
        print('json解码错误',e)


def getFirstImg(content):
    # print('123',content)
    for item in content:
        if item['type'] == 'img':
            # print(item['url'])
            return item['url'] 
            break
def getFirstText(content,num):
    i=0
    # print('123',content)
    for item in content:
        if item['type'] == 'text' :
            i+=1
            if i>1:
                # print(item['url'])
                text = item['content'] 
                text = f'{text[:num]}...'
                return text

@baike.route('/categories', methods=['GET'])
def getCategories():
    try:
        categories = db.session.query(articles.column).distinct().all()
        return jsonify({
            'code': 200,
            'message': '获取分类列表成功',
            'data': [category[0] for category in categories]
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取分类列表失败: {str(e)}',
            'data': None
        })
